/*
 * Created on Feb 15, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.ui.command;

import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import edu.mit.simile.longwell.schema.IStructuredSchema;
import edu.mit.simile.longwell.ui.Facade;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.FlairStructuredModel;
import edu.mit.simile.longwell.ui.InjectionManager;

/**
 * @author dfhuynh
 */
public class StartCommand extends CommandBase {
	final static private Logger s_logger = Logger.getLogger(StartCommand.class);

	final protected String m_template;

	/**
	 * @param injectionManager
	 */
	public StartCommand(InjectionManager injectionManager, String template) {
		super(injectionManager);
		m_template = template;
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.flair.IFlairCommand#execute(edu.mit.simile.flair.FlairMessage)
	 */
	public void execute(FlairMessage msg) throws ServletException {
		try {
			VelocityContext vcContext = createContext(msg);

			vcContext.put("facades", getFacades(msg));
			vcContext.put("schemas", getSchemas(msg));

			msg.m_ve.mergeTemplate(
				m_template,
				vcContext,
				msg.m_response.getWriter());
		} catch (Exception e) {
			s_logger.error(e);
			e.printStackTrace();
		}
	}

	static protected Set getFacades(FlairMessage msg) {
		Comparator comparator = null;
		if ("count".equals(msg.m_query.getFirstParamValue("sortFacades"))) {
			comparator = new Facade.CountComparator();
		} else {
			comparator = new Facade.LabelComparator();
		}

		SortedSet facades = new TreeSet(comparator);

		FlairStructuredModel flairStructuredModel = (FlairStructuredModel)
			msg.getProfile().getStructuredModel(FlairStructuredModel.class);

		facades.addAll(flairStructuredModel.getFacades());

		return facades;
	}

	protected Set getSchemas(FlairMessage msg) {
		SortedSet sSchemas = new TreeSet(new Comparator() {
			public boolean equals(Object obj) {
				return false;
			}

			public int compare(Object o1, Object o2) {
				IStructuredSchema ss1 = (IStructuredSchema) o1;
				IStructuredSchema ss2 = (IStructuredSchema) o2;

				return ss1.getURI().compareTo(ss2.getURI());
			}
		});

		sSchemas.addAll(msg.getProfile().getSchemaModel().getStructuredSchemas());

		return sSchemas;
	}
}
